using Entitas;
using UnityEngine;
using Const;

namespace Services
{
    public class LoadPrefabService:IComponentsAnyLoadPrefabListener
    {
        private Transform _settleParent;
        private Transform _movableParent;
        private Contexts _contexts;

        private static LoadPrefabService _instance;
       // public static LoadPrefabService Instance { private set; get; }=new LoadPrefabService();
        
        public static LoadPrefabService Instance
        {
            get
            {
                if (_instance == null)
                {
                    return new LoadPrefabService();
                }

                return _instance;
            }
        }
        
        public void Init(Contexts contexts, Transform gameController)
        {
            _contexts = contexts;
            contexts.game.CreateEntity().AddComponentsAnyLoadPrefabListener(this);
            CreateSubParent(gameController);
        }

        public void CreateSubParent(Transform parent)
        {
            _settleParent=new GameObject("settle").transform;
            _settleParent.SetParent(parent);
            _movableParent=new GameObject("movable").transform;
            _movableParent.SetParent(parent);
        }
        
        
        public void OnComponentsAnyLoadPrefab(GameEntity entity, string path)
        {
            Transform tempTrans;
            if (entity.isComponentsItem)
            {
                tempTrans = _movableParent;
            }
            else
            {
                tempTrans = _settleParent;
            }
            GameObject go = Resources.Load<GameObject>(path);
            var view = Object.Instantiate(go, tempTrans).GetComponent<IView>();
            view.Link(entity,_contexts.game);
        }
    }
}